import { gql, useMutation, useQuery } from "@apollo/client";
import { Button, Card, message, Space, Table } from "antd"
import { useSearchParams } from "react-router"
import { BaseFields } from "../../../queries/base";
import { TestPaperQuestionEntity, TestQuestionFields } from "../../../queries/test";
import { useColumns, useDataSource } from "../../../hooks/useTable";
import HeadBack from "../../../components/HeadBack";
import gqlError from "../../../libs/gql-error";
import useRole, { CREATE_POWER } from "../../../hooks/useRole";
import { TextDeleteButton } from "../../../components/BaseRoleButtonGroups";
import DelPopover from "../../../components/DelPopover";
import QuestionModal from "./QuestionModal";

export const QueryQuestionQuery = gql`
  query QueryQuestion(
    $id: Int!
  ){
    getQuestions(
      id: $id
    ){
      ${BaseFields}
      ${TestQuestionFields}
    }
  }
`
export interface QueryQuestionResult {
  getQuestions: TestPaperQuestionEntity[]
}
export const CreateQuestionMutation = gql`
  mutation CreateQuestion(
    $id: Int!,
    $name: String!,
    $type: String!,
    $answer: String,
    $content: String!,
    $score: Int!,
    $order: Int!,
    $count: Int,
    $right: Int,
    $help: String,
  ){
    createQuestion(
      sys_test_paperId: $id,
      name: $name,
      type: $type,
      answer: $answer,
      content: $content,
      score: $score,
      order: $order,
      count: $count,
      right: $right,
      help: $help,
    ){
      id
    }
  }
`
export const UpdateQuestionMutation = gql`
  mutation UpdateQuestion(
    $id: Int!,
    $name: String!,
    $type: String!,
    $answer: String,
    $content: String!,
    $score: Int!,
    $order: Int!,
    $count: Int,
    $right: Int,
    $help: String,
  ){
    updateQuestion(
      id: $id,
      name: $name,
      type: $type,
      answer: $answer,
      content: $content,
      score: $score,
      order: $order,
      count: $count,
      right: $right,
      help: $help,  
    ){
      id
    }
  }
`

export const DeleteQuestionMutation = gql`
  mutation DeleteQuestion(
    $id: Int! 
  ){
    deleteQuestion(
      id: $id
    ){
      id
    }
  }
`
const AdminQuestionPage = () => {
  const [searchParams] = useSearchParams()
  const groupId = searchParams.get("group")
  const testId = searchParams.get("test")
  const chapterId = searchParams.get("chapter")
  const paperId = parseInt(searchParams.get("paper") || "0")
  const { data, refetch, loading } = useQuery<QueryQuestionResult>(QueryQuestionQuery, {
    variables: {
      id: paperId
    }
  })
  const [create, { loading: createLoading }] = useMutation(CreateQuestionMutation, {
    onCompleted() {
      message.success("添加成功")
      refetch()
    },
    onError(error) {
      gqlError(error)
    },
  })
  const [update, { loading: updateLoading }] = useMutation(UpdateQuestionMutation, {
    onCompleted() {
      message.success("修改成功")
      refetch()
    },
    onError(error) {
      gqlError(error)
    },
  })
  const [del, { loading: deleteLoading }] = useMutation(DeleteQuestionMutation, {
    onCompleted() {
      message.success(`删除成功`)
      refetch()
    },
    onError(error) {
      gqlError(error)
    },
  })
  const hasRole = useRole("/test")

  const dataSource = useDataSource(data?.getQuestions)
  const columns = useColumns([{
    title: "ID",
    dataIndex: "id",
  }, {
    title: "题目",
    dataIndex: "name",
    key: "name",
    width: 200,
    render(__html) {
      return (
        <div dangerouslySetInnerHTML={{
          __html
        }}></div>
      )
    },
  }, {
    title: "类型",
    dataIndex: "type",
    key: "type",
    width: 100,
    render(text) {
      switch (text) {
        case "SINGLE":
          return "单选题"
        case "MULTIPLE":
          return "多选题"
        case "JUDGE":
          return "判断题"
        case "FILL":
          return "填空题"
        case "ANSWER":
          return "编程题"
        default:
          return text
      }
    },
  }, {
    title: "分值",
    dataIndex: "score",
    key: "score",
    width: 100,
  }, {
    title: "排序",
    dataIndex: "order",
    key: "order",
    width: 100,
  },
  {
    title: "操作",
    render: (_: any, record: any) => {
      return (
        <Space>
          <QuestionModal
            onFinish={variables => {
              update({
                variables: {
                  ...record,
                  ...variables
                }
              })
            }}
            record={record}
          >
            <Button type="link">查看</Button>
          </QuestionModal>
          <DelPopover
            onDelete={() => {
              del({
                variables: {
                  id: record.id
                }
              })
            }}
            disabled={deleteLoading}
          >
            <TextDeleteButton />
          </DelPopover>
        </Space>
      )
    }
  }])
  return (
    <Card>
      <HeadBack
        href={`/admin/test/${groupId}/group/${testId}/chapter/${chapterId}/paper`}
      />
      <QuestionModal
        onFinish={variables => {
          create({
            variables: {
              ...variables,
              id: paperId
            }
          })
        }}
      >
        <Button
          disabled={!hasRole([CREATE_POWER])}
          type="primary"
          loading={createLoading}
        >
          添加
        </Button>
      </QuestionModal>
      <Table
        dataSource={dataSource}
        loading={
          loading || updateLoading || deleteLoading
        }
        columns={columns}
        pagination={false}
      />
    </Card>
  )
}
export default AdminQuestionPage